<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS3 3D 实现图片旋转木马浏览效果</title>
    <style>
        .stage {
            width: 800px;
            height: 600px;
            margin: 100px auto;
            position: relative;
            perspective: 3000px;
        }

        .container {
            position: absolute;
            transform-style: preserve-3d;
            width: 480px;
            height: 270px;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            transition: transform 1s;
        }

        .container img {
            position: absolute;
            width: 480px;
            height: 270px;
        }
    </style>
</head>

<body>
    <div class="stage">
        <div class="container" id="container"></div>
    </div>
</body>

<script>
    const IMG_COUNT = 9;
    const ROTATE_ANGLE = 360 / IMG_COUNT;
    const IMG_WIDTH = 480;

    var container = document.getElementById("container");
    var frontImgIndex = 0;

    // 批量添加图片文件
    var imgs = '';
    var translateZ = (IMG_WIDTH / 2) / Math.tan(ROTATE_ANGLE / 2 * Math.PI / 180) + 50;
    for (let i = 1; i <= IMG_COUNT; i++) {
        imgs += `<img src='./images/${i}.jpg' style='transform:rotateY(${(i - 1) * ROTATE_ANGLE}deg) translateZ(${translateZ}px)'>`;
    }
    container.innerHTML = imgs;

    // // 图片自动旋转
    // function swing() {
    //     container.style.transform = `translate(-50%, -50%) rotateY(${++frontImgIndex * ROTATE_ANGLE}deg)`;
    //     setTimeout(swing, 1800)
    // }
    // var swingTimeout = setTimeout(swing, 1800);

    // 点击图片旋转
    var imgElements = container.childNodes;
    for (let i = 0; i < imgElements.length; i++) {
        const element = imgElements[i];
        element.addEventListener('click', function () {
            container.style.transform = `translate(-50%, -50%) rotateY(${++frontImgIndex * ROTATE_ANGLE}deg)`;
        }, false);
    }
</script>

</html>